<?php
namespace app\admin\service;

use app\common\model\MachineModel;
use app\common\model\OperateModel;
use app\common\model\UserModel;
use app\common\model\ModuleModel;

class MachineService
{
    private static $model;
    private static $userModel;
    private static $operateModel;
    private static $moduleModel;

    public function __construct(MachineModel $machineModel,
                                UserModel $userModel,
                                ModuleModel $moduleModel,
                                OperateModel $operateModel)
    {
        self::$model = $machineModel;
        self::$userModel = $userModel;
        self::$operateModel = $operateModel;
        self::$moduleModel = $moduleModel;
    }

    /**
     * 显示测试仪列表
     * User: zhouyao
     * Date: 2018/12/4
     * Time: 10:53 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($params)
    {
        if (empty($params) || !isset($params['page']) || !isset($params['limit'])) {
            return app_fail(9997);
        }

        $count = self::$model->count();
        if ($count < 1) {
            return ['data' => [], 'count' => (int) $count];
        }

        $result = self::$model->page($params['page'], $params['limit'])->select();
        $userArr = array_column($result->toArray(), 'user_id');
        $user = self::$userModel->whereIn('id', $userArr)->column('nickname', 'id');
        $result->each(function ($item) use ($user) {
            $item->nickname = $user[$item->user_id];
            $item->create_time = date('Y-m-d', $item->create_time);
            return $item;
        });

        return ['data' => $result, 'count' => (int) $count];
    }

    /**
     * 删除测试仪器
     * User: zhouyao
     * Date: 2018/12/9
     * Time: 7:30 PM
     * @param $params
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delete($params)
    {
        if (empty($params) || !isset($params['id'])) {
            return app_fail(9997);
        }
//        $userInfo = self::$userModel->where(['id'=>$params['guid']])->find();
//        if ($userInfo->type != 1) {
//            return app_fail(1000);
//        }
        $row = self::$model->where('id', '=', $params['id'])->find();
        try {
            // 模块也需要删除
            self::$moduleModel->where('machine_code', '=', $row['machine_code'])->delete();
            self::$model->where('id', '=', $params['id'])->delete();
        } catch (\Exception $e) {
            return app_fail(9980);
        }
    }

    /**
     * 获取当前用户能查看的测试仪
     * @param $params
     * @return array|void
     */
    public function machineList($params)
    {
        if (empty($params) || !isset($params['page']) || !isset($params['limit'])) {
            return app_fail(9997);
        }
        $userInfo = self::$userModel->where(['id'=>$params['guid']])->find();
        $where = '';
        if($userInfo->type == 2)
        {
            $where1 = [
                ['user_id', '=', $params['guid']],
                ['machine_code', '<>', 'null'],
            ];
            $machine_code_arr = self::$operateModel->where($where1)
                ->distinct(true)
                ->field('machine_code')
                ->page($params['page'], $params['limit'])
                ->column('machine_code');
            $machine_code_str = "'".implode("','", $machine_code_arr)."'";
            $where = " machine_code in ($machine_code_str) or user_id = ".$params['guid'];
        }
        $count = self::$model->where($where)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => (int) $count];
        }

        $result = self::$model->where($where)->page($params['page'], $params['limit'])->select();
        $userArr = array_column($result->toArray(), 'user_id');
        $user = self::$userModel->whereIn('id', $userArr)->column('nickname', 'id');
        $result->each(function ($item) use ($user) {
            $item->nickname = $user[$item->user_id];
            $item->create_time = date('Y-m-d', $item->create_time);
            return $item;
        });

        return ['data' => $result, 'count' => (int) $count];
    }

    /**
     * zws
     * 获取模块
     * @param $params
     * @return array|void
     */
    public function get_module($params)
    {
        if (empty($params) || !isset($params['page']) || !isset($params['limit']) || !isset($params['machine_code'])) {
            return app_fail(9997);
        }
        if(empty($params['machine_code']))
        {
            return app_fail(8299);
        }
        $userInfo = self::$userModel->where(['id'=>$params['guid']])->find();
        if ($userInfo->type != 1) {
            return app_fail(1000);
        }
        $params['page'] = $params['page'] ? $params['page'] : 1;
        $params['limit'] = $params['limit'] ? $params['limit'] : 20;
        $where1 = ['machine_code'=>$params['machine_code']];
        $count = self::$moduleModel->where($where1)->count();
        if($count < 1)
        {
            return ['data' => [], 'count' => 0];
        }
        $module_datas = self::$moduleModel->where($where1)->select();
        $module_codes = [];
        foreach ($module_datas as $v)
        {
            $module_codes[] = $v['module_code'];
        }
        $last_module_datas = $this->get_last_module($module_codes);
        foreach ($module_datas as $k=>$v)
        {
            $module_datas[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
            $module_datas[$k]['update_time'] = $v['update_time'] ? date('Y-m-d H:i:s', $v['update_time']) : '';
            if(isset($last_module_datas[$v['module_code']]))
            {
                $last_module_data = $last_module_datas[$v['module_code']];
                $module_datas[$k]['module_name'] = $last_module_data['module_name'];
                $module_datas[$k]['content'] = $last_module_data['content'];
                $module_datas[$k]['module_type'] = $last_module_data['module_type'];
                $module_datas[$k]['remark'] = $last_module_data['remark'];
                $module_datas[$k]['update_time'] = $last_module_data['create_time'] ? date('Y-m-d H:i:s', $last_module_data['create_time']) : '';
                $module_datas[$k]['nickname'] = self::$userModel->where(['id' => $v['user_id']])->column('nickname')[0];
            }
        }
        return ['data' => $module_datas, 'count' => (int) $count];
    }
    public function get_last_module($module_codes)
    {
        if(empty($module_codes))
        {
            return [];
        }
        $module_codes_str = "'".implode("','", $module_codes)."'";
        $where = " module_code in ($module_codes_str)";
        $sql = "select a.* from (select * from module_log where $where order by id desc) a GROUP BY a
.module_code";
        $data = [];
        $result = db('module_log')->query($sql);
        if($result)
        {
            foreach ($result as $v)
            {
                $v['module_id'] = $v['module_code'];
                $data[$v['module_code']] = $v;
            }
        }
        return $data;
    }


}